package com.itwang.common;

import java.io.*;

//文件操作
public class FileUtil {
	//默认ip存储文件的路径
	private static final String DEFAULT_FILE_PATH = "ips.txt";
	private static String FILE_PATH ;
	static {
		FILE_PATH = PropertiesUtil.getKey("ipFilePath");
		if (FILE_PATH == "" || FILE_PATH == null){
			FILE_PATH = DEFAULT_FILE_PATH;
		}
	}
	
	//从文件中读取ip相关内容并返回string
	public static String getIpFile() throws IOException {
		File file = new File(FILE_PATH);
		if (file.exists()) {
			
			FileInputStream fileInputStream = new FileInputStream(file);
			
			byte[] bytes = new byte[1024];
			String result = "";
			int len = 0;
			while ((len = fileInputStream.read(bytes)) != -1) {
				result += new String(bytes,0,len);
			}
			
			fileInputStream.close();
			return result;
			
		} else {
			file.createNewFile();
			return "";
		}
	}
	
	// 向文件中写入ip地址
	public static void setIpFile(String s) throws IOException {
		File file = new File(FILE_PATH);
		//文件写入默认覆盖,追加写入加入第二个参数为true
		FileOutputStream fileOutputStream = new FileOutputStream(file,false);
		if (file.exists()) {
			fileOutputStream.write(s.getBytes());
		}else {
			file.createNewFile();
			fileOutputStream.write(s.getBytes());
		}
		fileOutputStream.close();
	}
}
